package tiled.util;

import java.util.Iterator;
import java.util.Vector;

public class NumberedSet
{
    private Vector data;

    public NumberedSet()
    {
        data = new Vector();
    }

    public Object get(int id)
    {
        try
        {
            return data.get(id);
        }
        catch(ArrayIndexOutOfBoundsException e) {}

        return null;
    }

    public boolean containsId(int id)
    {
        return get(id) != null;
    }

    public int put(int id, Object o) throws IllegalArgumentException
    {
        if (id < 0)
            throw new IllegalArgumentException();

        for (int i = id - data.size(); i > 0; i--)
        {
            data.add(null);
        }

        data.add(id, o);
        return id;
    }

    public void remove(int id)
    {
        data.remove(id);
    }

    public int getMaxId()
    {
        int maxId = data.size() - 1;

        while(maxId >= 0)
        {
            if (data.get(maxId) != null)
            {
                break;
            }
            maxId--;
        }

        return maxId;
    }

    public Iterator iterator()
    {
        return data.iterator();
    }

    public int add(Object o)
    {
        int id = getMaxId() + 1;
        put(id, o);
        return id;
    }

    public int indexOf(Object o)
    {
        return data.indexOf(o);
    }

    public boolean contains(Object o)
    {
        return data.contains(o);
    }

    public int findOrAdd(Object o)
    {
        int id = indexOf(o);
        if (id != -1)
            return id;
        return add(o);
    }

    public int size()
    {
        return data.size();
    }
}
